package com.huike.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;

@Service
public class CaptchaServiceImpl {

    private static final String REDIS_KEY_PREFIX = "kaptcha:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String generateCaptcha() {
        // 创建kaptcha对象
        DefaultKaptcha kaptcha = new DefaultKaptcha();

        // 设置kaptcha属性
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "150");
        properties.setProperty("kaptcha.image.height", "50");
        kaptcha.setConfig(new Config(properties));

        // 生成验证码
        String text = kaptcha.createText();
        BufferedImage image = kaptcha.createImage(text);
        System.out.println(text);
        redisTemplate.opsForValue().set(REDIS_KEY_PREFIX,text);
        // 将验证码图片转换成base64编码的文本格式
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        return base64Image;
    }

    public boolean validateCaptcha(String key, String captchaString) {
        String storedCaptcha = redisTemplate.opsForValue().get(REDIS_KEY_PREFIX + key);
        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(captchaString)) {
            // 验证通过后删除Redis中的验证码
            redisTemplate.delete(REDIS_KEY_PREFIX + key);
            return true;
        }
        return false;
    }

}